<template>
  <div v-if="plugin" class="plugin-detail-container">
    <a-page-header
      :title="plugin.name"
      :subtitle="`版本: ${plugin.info.version}`"
      @back="goBack"
    >
      <template #extra>
        <a-space>
          <a-tag v-if="plugin.hasUpdate" color="orange">有更新</a-tag>
          <a-tag v-if="plugin.pinned" color="blue">置顶</a-tag>
          <a-tag color="arcoblue">{{ GettagName(plugin.type) }}</a-tag>
        </a-space>
      </template>
    </a-page-header>

    <div class="plugin-detail-content">
      <div class="plugin-detail-header">
        <div class="plugin-logo">
          <img :src="getPluginLogo(plugin)" alt="插件图标" />
        </div>
        <div class="plugin-info">
          <h2>{{ plugin.name }}</h2>
          <p class="plugin-description">{{ plugin.info.description }}</p>
          <div class="plugin-meta">
            <a-space>
              <a-tag v-for="tag in plugin.tags" :key="tag">{{ tag }}</a-tag>

              <span v-if="plugin.info.author && plugin.info.author.name">
                作者: {{ plugin.info.author.name }}
              </span>
              <span v-if="plugin.info.updated">
                更新时间: {{ formatDate(plugin.info.updated) }}
              </span>
            </a-space>
          </div>
          <div class="plugin-actions">
            <template v-if="plugin.enabled">
              <a-button v-if="plugin.type === 'datasource' || plugin.type === 'app'" type="primary" @click="openDataSourceModal">设置数据源</a-button>

              <a-button v-if="plugin.core !== 'core'" :loading="loading" type="outline" status="danger" @click="uninstallPlugin">卸载</a-button>
            </template>
            <template v-else>
              <a-button type="primary" :loading="loading" @click="installPlugin">安装</a-button>
            </template>
          </div>
        </div>
      </div>

      <a-divider />

      <a-tabs default-active-key="readme">
        <a-tab-pane key="readme" title="说明">
          <div v-if="plugin.readme" class="markdown-content">
            <div v-html="renderMarkdown(plugin.readme)"></div>
          </div>
          <a-empty v-else description="暂无说明文档" />
        </a-tab-pane>
        <a-tab-pane key="changelog" title="版本历史">
          <div v-if="plugin.changelog" class="markdown-content">
            <div v-html="renderMarkdown(plugin.changelog)"></div>
          </div>
          <a-empty v-else description="暂无版本记录" />
        </a-tab-pane>
        <a-tab-pane key="versions" title="版本记录">
          <a-timeline v-if="pluginVersions && pluginVersions.length > 0">
            <a-timeline-item
              v-for="item in pluginVersions"
              :key="item.version"
              :dot-color="item.version === plugin.info.version ? 'blue' : 'gray'"
            >
              <div class="version-item">
                <h4>
                  {{ item.version }}
                  <a-tag v-if="item.version === plugin.info.version" color="blue">当前版本</a-tag>
                </h4>
                <p v-if="item.created">发布日期: {{ item.created }}</p>

                <div v-if="item.commit" class="version-notes">
                  <div v-html="renderMarkdown(item.commit)"></div>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
          <a-empty v-else description="暂无版本历史" />
        </a-tab-pane>
        <a-tab-pane key="dependencies" title="依赖(待开发)" disabled>
          <div v-if="plugin.dependencies && plugin.dependencies.plugins && plugin.dependencies.plugins.length > 0">
            <a-descriptions :column="1" size="medium" bordered>
              <a-descriptions-item label="CaiPu 版本">
                {{ plugin.dependencies.caiPuVersion || '无要求' }}
              </a-descriptions-item>
            </a-descriptions>
            <a-divider />
            <h3>插件依赖</h3>
            <a-table :data="plugin.dependencies.plugins" :pagination="false">
              <template #columns>
                <a-table-column title="名称" data-index="name" />
                <a-table-column title="类型" data-index="type" />
                <a-table-column title="版本" data-index="version" />
              </template>
            </a-table>
          </div>
          <a-empty v-else description="暂无依赖信息" />
        </a-tab-pane>
        <a-tab-pane key="screenshots" title="截图(待开发）" disabled>
          <div v-if="plugin.info.screenshots && plugin.info.screenshots.length > 0" class="screenshots-container">
            <div v-for="(screenshot, index) in plugin.info.screenshots" :key="index" class="screenshot-item">
              <img :src="screenshot.path" :alt="screenshot.name" />
              <p>{{ screenshot.name }}</p>
            </div>
          </div>
          <a-empty v-else description="暂无截图" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  <div v-else class="loading-container">
    <a-spin tip="加载中..."></a-spin>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message, Notification } from '@arco-design/web-vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { GettagName } from './index'
import type { PluginDTO } from '@/types/plugins'
import { install, queryPlugin, queryPluginFromSite, queryPluginVersionFromSite, uninstall } from '@/apis/system/plugins'
import { useTabsStore } from '@/stores'

export default defineComponent({
  name: 'PluginDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const plugin = ref<PluginDTO | null>(null)
    const pluginVersions = ref([])
    const loading = ref(false)
    const tabsStore = useTabsStore()

    const getPluginVersion = async (id: string) => {
      try {
        loading.value = true
        const { data } = await queryPluginVersionFromSite(id)
        pluginVersions.value = data.versions
      } catch (error) {
        console.log(`获取插件版本失败: ${error.message}`)
      }
    }
    const fetchPluginDetail = async () => {
      const pluginId = route.params.id as string
      if (!pluginId) {
        Message.error('插件ID不存在')
        router.push('/plugin/index')
        return
      }

      try {
        loading.value = true

        const { code, data } = await queryPlugin(pluginId)
        if (code === 200) {
          plugin.value = data
        } else {
          // 远程查找
          const { data } = await queryPluginFromSite(pluginId)
          plugin.value = data
        }
      } catch (error) {
        Message.error(`获取插件详情失败: ${error.message}`)
        router.push('/plugin/index')
      } finally {
        tabsStore.setTabTitle(plugin.value?.name || '插件详情')
        getPluginVersion(pluginId)
        loading.value = false
      }
    }

    const goBack = () => {
      router.back()
    }

    const installPlugin = async () => {
      if (!plugin.value) return

      try {
        loading.value = true
        Notification.warning({
          id: 'install_plugin',
          title: '提示',
          content: `正在安装插件[${plugin.value.name}],请等待...`,
          duration: 0,
        })
        await install(plugin.value.id, plugin.value.info.version)

        setTimeout(() => {
          Notification.success({
            id: 'install_plugin',
            title: '提示',
            content: '插件安装成功!',
            duration: 2000,
          })
        }, 1000)
        Message.success(`插件 ${plugin.value.name} 安装成功`)
        // 重新获取插件信息
        await fetchPluginDetail()
      } catch (error) {
        Message.error(`安装失败: ${error.message}`)

        setTimeout(() => {
          Notification.error({
            id: 'install_plugin',
            title: '提示',
            content: `插件安装失败：${error.message}`,
            duration: 2000,
          })
        }, 1000)
      } finally {
        loading.value = false
      }
    }

    const uninstallPlugin = async () => {
      if (!plugin.value) return

      try {
        loading.value = true
        await uninstall(plugin.value.id)
        Message.success(`插件 ${plugin.value.name} 卸载成功`)
        router.push('/plugin/index')
        tabsStore.closeCurrent(route.path)
      } catch (error) {
        Message.error(`卸载失败: ${error.message}`)
      } finally {
        loading.value = false
      }
    }

    // 插件数据源设置
    const openDataSourceModal = () => {
      const pluginlocalSet = ['wework', 'email', 'caipu-site']
      // 判断是不是本地的，是跳转本地设置
      if (pluginlocalSet.includes(plugin.value.id)) {
      // 将插件名称生成数组
        router.push({ path: `/plugins/set`, query: { tab: plugin.value.id } })
        return
      }
      router.push({ path: `/app/${plugin.value.id}/setting`, query: { } })
    }

    const getPluginLogo = (plugin: PluginDTO) => {
      let logo: string = ''
      // 如果插件有自定义logo，优先使用
      if (plugin.info.logos && plugin.info.logos.large) {
        logo = plugin.info.logos.large
      } else {
        return 'http://www.gocpu.cn/logo.png'
      }
      if (logo.startsWith('http')) {
        return logo
      }
      return `${import.meta.env.VITE_API_BASE_URL}/app/${plugin.id}/${logo}`
    }

    const renderMarkdown = (content: string) => {
      if (!content) return ''
      // 使用marked解析markdown，并使用DOMPurify清理HTML
      return DOMPurify.sanitize(marked(content))
    }

    const formatDate = (dateString: string) => {
      try {
        const date = new Date(dateString)
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
        })
      } catch (e) {
        return dateString
      }
    }

    onMounted(() => {
      fetchPluginDetail()
    })

    return {
      plugin,
      pluginVersions,
      loading,
      GettagName,
      goBack,
      getPluginVersion,
      installPlugin,
      uninstallPlugin,
      openDataSourceModal,
      getPluginLogo,
      renderMarkdown,
      formatDate,
    }
  },
})
</script>

<style scoped>
.plugin-detail-container {
  padding: 24px;
  max-width: 1200px;
  min-width: 800px;
  margin: 14px auto;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow:auto;
}

.plugin-detail-header {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.plugin-logo {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.plugin-logo img {
  max-width: 80%;
  max-height: 80px;
  object-fit: contain;
}

.plugin-info {
  flex: 1;
}

.plugin-description {
  margin: 12px 0;
  color: var(--color-text-2);
  font-size: 14px;
  line-height: 1.6;
}

.plugin-meta {
  margin-bottom: 16px;
  color: var(--color-text-3);
  font-size: 14px;
}

.plugin-actions {
  display: flex;
  gap: 8px;
}

.markdown-content {
  padding: 16px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  line-height: 1.6;
}

.version-item {
  margin-bottom: 16px;
}

.version-notes {
  margin-top: 8px;
  padding: 8px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  font-size: 14px;
}

.screenshots-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.screenshot-item {
  border: 1px solid var(--color-border);
  border-radius: 4px;
  overflow: hidden;
}

.screenshot-item img {
  width: 100%;
  height: auto;
  object-fit: cover;
}

.screenshot-item p {
  padding: 8px;
  margin: 0;
  text-align: center;
  background-color: var(--color-fill-2);
  font-size: 14px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}
</style>
